import React, { useEffect, useState, useRef } from 'react';
import { connect, history } from 'umi';
import { Form, Button, Col, Row, Space, Card, notification } from 'antd';
import FormCondition from '@/components/FormCondition';
import DrawerCondition from '@/components/DrawerCondition';
import EditorForm from '@/components/EditorForm';
import uploadOss from '@/utils/aliOssUpload';
import { goodsType_status } from '@/common/contact';
import moment from 'moment';
import MaterialModel from '@/components/MaterialModel';
import PackagingModel from '@/components/PackagingModel';
import MainAdminTable from '@/components/MainAdminTable';
import Commission from '@/components/Commission';
import PopImgShow from '@/components/PopImgShow';
import ShareImage from '@/assert/image/shareImageCode.png';
import SelectDevAdmin from '@/components/SelectDevAdmin'
import './index.less';

const CreateOnDemand = (props) => {
  const { history, loading, dispatch } = props;
  const { location } = history;
  const { query } = location;
  const { id, handleType = 'edit' } = query;
  const [data, setData] = useState({});
  const [commission, setCommission] = useState([]);
  const packagingRef = useRef(null);
  const materialRef = useRef(null);
  const EditContent = useRef(null);
  const { goodsPackageList = [], materialInfoList = [] } = data;
  const [MainAdminList, setMainAdminList] = useState([]);
  const [helpAdminList, sethelpAdminList] = useState([]);
  const [form] = Form.useForm();
  const [selectDevData, setSelectDevData] = useState([]);
  const [defaultSetting, setDefaultSetting] = useState({
    upType: 'now',
    showFlag: '1',
    priceType: 'free',
    signFlag: '0'
  });
  const { upType, showFlag, priceType, signFlag } = defaultSetting;
  const [content, setContent] = useState(''); // 输入的富文本内容
  const { content: oldContent } = data;
  useEffect(() => {
    if (id) {
      dispatch({
        type: 'liveStreaming/fetchVideoCourseDetail',
        payload: { goodsId: id },
        callback: (e) => {
          const {
            goodsBaseInfo = {},
            goodsPackageList = [],
            materialInfoList = [],

          } = e;
          const { picture, upType } = goodsBaseInfo;
          setData({
            ...goodsBaseInfo,
            cover: picture,
            upDelayTime: upType === 'delay' ? moment(upDelayTime, 'YYYY-MM-DD HH:mm:ss') : '',
            goodsPackageList,
            materialInfoList,
          });

        },
      });
    }
  }, []);
  useEffect(() => {
    if (id && data.id) {
      if (id) {
        form.setFieldsValue({
          upType: data.upType,
          showFlag: data.showFlag,
          priceType: data.priceType,
        })
      }
      setDefaultSetting({
        upType: data.upType,
        showFlag: data.showFlag,
        priceType: data.priceType,
      });
      EditContent.current.reloadEdit();
    }
  }, [data]);
  const fetchRoleEdit = () => {
    let goodsPackageList = packagingRef.current.getPackaging();
    let goodsPackageFlag = goodsPackageList.reduce((item, val) => {
      if (!item) {
        return item;
      } else {
        if (val.chooseType === 'any' && (!val.chooseAmount || val.chooseAmount === 0)) {
          console.log(val);
          notification.warning({
            message: '错误提示',
            description: `${goodsType_status[val.packageGoodsType]} 选择任何后 打包数量不能为0`,
          });
          return false;
        } else {
          return item;
        }
      }
    }, true);
    if (!goodsPackageFlag) {
      return;
    } else if (!content) {
      notification.warning({
        message: '错误提示',
        description: `请填写详情`,
      });
    } else {
      form.validateFields().then(async (values) => {
        const { picture } = values;

        const materialIdList = materialRef.current.getMaterial();

        let img = await uploadOss(picture);
        const {
          goodsDesc,
          goodsName,
          showFlag,
          upType,
          upDelayTime,
          price,
          priceType,
          oriPrice,
          minPrice,
        } = values;
        dispatch({
          type: 'liveStreaming/fakeSaveVideoCourse',
          payload: {
            id: handleType === 'edit' ? id : '',
            goodsBaseInfo: {
              content,
              goodsDesc,
              picture: img.toString(),
              goodsName,
              id: handleType === 'edit' ? id : '',
              showFlag,
              upType,
              upDelayTime:
                upType === 'delay' ? moment(upDelayTime).format('YYYY-MM-DD HH:mm:ss') : '',
              price,
              priceType,
              oriPrice,
              materialIdList,
              minPrice,
            },
            goodsPackageList,
          },
          callback: () => {
            history.goBack();
          },
        });
      });
    }
  };

  const formItems = [
    {
      label: '名称',
      name: 'goodsName',
    },
    {
      label: '封面',
      name: 'picture',
      type: 'upload',
      extra:
        '建议图片比例16:9，支持 jpg、png 格式，大小不超过5MB，最佳分辨率750*422px,并自动取第一张做直播宣传封面',
      maxFile: 15,
    },
    {
      label: '商品明细',
      name: 'goodsDesc',
      type: 'textArea',
      rules: [{ required: false }],
      placeholder: '商品对应内容',
    },
    {
      label: '分享图',
      name: 'shareImg',
      extra: (
        <div>
          建议图片分辨率为560x728,分享码位于右下角居下40px居右32px。如下图：
          <div style={{ marginTop: 12 }}>
            <PopImgShow width={80} url={ShareImage}></PopImgShow>
          </div>
        </div>
      ),
      maxFile: 1,
      type: 'upload',
      rules: [{ required: false }],
    },
    {
      type: 'noForm',
      formItem: (
        <Row>
          <Col span={6} style={{ textAlign: 'right' }} className="">
            <span style={{ color: '#ff4d4f' }}>*</span> 详情：
          </Col>
          <Col span={17} className="">
            {' '}
            <EditorForm
              ref={EditContent}
              initEditor={id ? false : true}
              content={oldContent}
              editCallback={(val) => setContent(val)}
            ></EditorForm>
          </Col>
        </Row>
      ),
    },
    {
      type: 'noForm',
      formItem: (
        <MaterialModel
          defaultDataList={materialInfoList}
          ref={materialRef}
          detail={data}
        ></MaterialModel>
      ),
    },
  ];

  const formItemsGroup3 = [
    {
      label: '售卖方式',
      name: 'priceType',
      type: 'radio',
      select: {
        free: '免费',
        money: '付费',
      },
      onChange: (e) => {
        setDefaultSetting({
          ...defaultSetting,
          priceType: e.target.value,
        });
      },
    },
    {
      label: '原价',
      rules: [
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      name: 'oriPrice',
      type: 'number',
      visible: priceType === 'money',
    },
    {
      label: '售价',
      name: 'price',
      rules: [
        { required: true },
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      type: 'number',
      visible: priceType === 'money',
    },
    {
      label: '底价',
      name: 'minPrice',
      type: 'number',
      rules: [
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      visible: priceType === 'money',
    },
    {
      type: 'noForm',
      formItem: (
        <PackagingModel
          disabled={priceType !== 'money'}
          defaultDataList={goodsPackageList}
          ref={packagingRef}
          detail={data}
        >
          {' '}
        </PackagingModel>
      ),
    },
  ];
  const formItemsGroup4 = [
    {
      label: '上架类型',
      name: 'upType',
      type: 'radio',
      onChange: (e) => {
        setDefaultSetting({
          ...defaultSetting,
          upType: e.target.value,
        });
      },
      select: {
        now: '立刻上架',
        delay: '定时上架',
        off: '暂不上架',
      },
    },
    {
      label: '定时上架时间',
      name: 'upDelayTime',
      type: 'dataPicker',
      format: 'YYYY-MM-DD HH:mm',
      visible: upType === 'delay',
    },
    {
      label: '是否显示在店铺',
      name: 'showFlag',
      type: 'radio',
      select: {
        0: '否',
        1: '是',
      },
    },
  ];
  return (
    <Card title={id ? '编辑点播' : '新建点播'} style={{ position: 'relative' }}>
      <Row>
        <Col span={18}>
          <div className="createLive-manage-part">
            <div className="createLive-part-title">
              <div className="createLive-title-line"></div>
              <div className="createLive-part-title-word">基本信息</div>
            </div>
          </div>
          <FormCondition
            form={form}
            formItems={formItems}
            initialValues={{
              ...data,
              ...defaultSetting,
            }}
          ></FormCondition>
          <div className="createLive-manage-part">
            <div className="createLive-part-title">
              <div className="createLive-title-line"></div>
              <div className="createLive-part-title-word">商品信息</div>
            </div>
          </div>
          <FormCondition
            form={form}
            formItems={formItemsGroup3}
            initialValues={{ ...data }}
          ></FormCondition>
          <div className="createLive-manage-part">
            <div className="createLive-part-title">
              <div className="createLive-title-line"></div>
              <div className="createLive-part-title-word">上架设置</div>
            </div>
          </div>
          <FormCondition
            form={form}
            formItems={formItemsGroup4}
            initialValues={{ ...data, upType, showFlag }}
          ></FormCondition>
        </Col>
        <div className="create_upload_btn">
          <Button onClick={() => fetchRoleEdit()} type="primary">
            {id ? '保存课程' : '创建课程'}
          </Button>
        </div>
      </Row>
    </Card>
  );
};
export default connect(({ loading }) => ({
  loading: loading.effects['liveStreaming/fetchVideoCourseDetail'],
}))(CreateOnDemand);
